<template>
  <div class="qrcode-container">
    <div class="qrcode-box flex justify-center items-center">
      <canvas
        ref="canvasRef"
        style="border: 1px solid #ccc; border-radius: 5px"
        :style="{ width: props.canvasSize + 'px', height: props.canvasSize + 'px' }"
      ></canvas>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import QRCode from 'qrcode'

const finalImage = ref<any>(null)
const props = defineProps({
  link: { type: String, default: 'https://example.com' }, // 二维码内容
  centerText: { type: String, default: '中间文字' }, // 中间文本
  canvasSize: { type: Number, default: 300 }, // 画布尺寸
  qrSize: { type: Number, default: 260 }, // 二维码尺寸（小于画布）
  qrColor: { type: String, default: '#2492ec' }, // 二维码颜色
  // 中心图标配置
  centerIcon: { type: String, default: '' }, // 中心图标URL
  iconSize: { type: Number, default: 40 }, // 图标大小
  showBackground: { type: Boolean, default: true }, // 是否显示白色背景
  centerType: { type: String, default: 'text' }, // 'text' | 'icon' | 'both'
})
const canvasRef = ref<any>(null)

const generateQRCode = async () => {
  // 设置Canvas实际像素尺寸
  const canvas = canvasRef.value
  canvas.width = props.canvasSize
  canvas.height = props.canvasSize

  const qrDataURL: any = await QRCode.toDataURL(props.link, {
    width: props.qrSize,
    margin: 0,
    errorCorrectionLevel: 'H', // 使用高容错级别，支持覆盖部分区域
    color: {
      dark: props.qrColor,
      light: '#fff',
    },
  })

  const ctx = canvas.getContext('2d')
  const img = new Image()
  img.src = qrDataURL

  await new Promise((resolve: any) => {
    img.onload = async () => {
      // 清空画布
      ctx.clearRect(0, 0, props.canvasSize, props.canvasSize)

      // 居中绘制二维码
      const qrX = (props.canvasSize - props.qrSize) / 2
      const qrY = (props.canvasSize - props.qrSize) / 2

      ctx.drawImage(img, qrX, qrY, props.qrSize, props.qrSize)

      // 中心位置
      const centerX = props.canvasSize / 2
      const centerY = props.canvasSize / 2

      // 根据类型绘制中心内容
      if (props.centerType === 'icon' && props.centerIcon) {
        await drawCenterIcon(ctx, centerX, centerY)
      } else if (props.centerType === 'text') {
        drawCenterText(ctx, centerX, centerY)
      } else if (props.centerType === 'both' && props.centerIcon) {
        await drawIconWithText(ctx, centerX, centerY)
      }

      // 导出最终图片
      finalImage.value = canvas.toDataURL('image/png')
      resolve()
    }
  })
}

// 绘制中心图标
const drawCenterIcon = async (ctx: CanvasRenderingContext2D, centerX: number, centerY: number) => {
  if (!props.centerIcon) return

  // 绘制白色圆形背景
  if (props.showBackground) {
    const bgRadius = props.iconSize / 2 + 8
    ctx.beginPath()
    ctx.arc(centerX, centerY, bgRadius, 0, 2 * Math.PI)
    ctx.fillStyle = '#ffffff'
    ctx.fill()

    // 添加边框
    ctx.strokeStyle = '#e0e0e0'
    ctx.lineWidth = 1
    ctx.stroke()
  }

  // 加载并绘制图标
  return new Promise<void>((resolve) => {
    const iconImg = new Image()
    iconImg.crossOrigin = 'anonymous'
    iconImg.onload = () => {
      const iconX = centerX - props.iconSize / 2
      const iconY = centerY - props.iconSize / 2

      // 绘制圆形裁剪的图标
      ctx.save()
      ctx.beginPath()
      ctx.arc(centerX, centerY, props.iconSize / 2, 0, 2 * Math.PI)
      ctx.clip()
      ctx.drawImage(iconImg, iconX, iconY, props.iconSize, props.iconSize)
      ctx.restore()

      resolve()
    }
    iconImg.onerror = () => {
      console.error('图标加载失败:', props.centerIcon)
      resolve()
    }
    iconImg.src = props.centerIcon
  })
}

// 绘制中心文字
const drawCenterText = (ctx: CanvasRenderingContext2D, centerX: number, centerY: number) => {
  if (props.showBackground) {
    // 计算文字尺寸
    ctx.font = 'bold 16px Arial'
    const textMetrics = ctx.measureText(props.centerText)
    const textWidth = textMetrics.width
    const bgPadding = 12
    const bgWidth = textWidth + bgPadding * 2
    const bgHeight = 32

    // 绘制圆角矩形背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.95)'
    ctx.beginPath()
    ctx.roundRect(centerX - bgWidth / 2, centerY - bgHeight / 2, bgWidth, bgHeight, 8)
    ctx.fill()

    // 添加边框
    ctx.strokeStyle = '#e0e0e0'
    ctx.lineWidth = 1
    ctx.stroke()
  }

  // 绘制文字
  ctx.font = 'bold 16px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillStyle = '#333333'
  ctx.fillText(props.centerText, centerX, centerY)
}

// 绘制图标+文字组合
const drawIconWithText = async (
  ctx: CanvasRenderingContext2D,
  centerX: number,
  centerY: number,
) => {
  const iconSize = props.iconSize
  const spacing = 8
  const totalHeight = iconSize + 24 + spacing
  const bgWidth = Math.max(iconSize + 20, 80)

  // 绘制整体背景
  if (props.showBackground) {
    ctx.fillStyle = 'rgba(255, 255, 255, 0.95)'
    ctx.beginPath()
    ctx.roundRect(centerX - bgWidth / 2, centerY - totalHeight / 2, bgWidth, totalHeight, 10)
    ctx.fill()

    // 添加边框
    ctx.strokeStyle = '#e0e0e0'
    ctx.lineWidth = 1
    ctx.stroke()
  }

  // 绘制图标
  const iconY = centerY - totalHeight / 2 + iconSize / 2 + 10
  if (props.centerIcon) {
    await new Promise<void>((resolve) => {
      const iconImg = new Image()
      iconImg.crossOrigin = 'anonymous'
      iconImg.onload = () => {
        const iconX = centerX - iconSize / 2
        const iconYPos = iconY - iconSize / 2
        ctx.drawImage(iconImg, iconX, iconYPos, iconSize, iconSize)
        resolve()
      }
      iconImg.onerror = () => resolve()
      iconImg.src = props.centerIcon
    })
  }

  // 绘制文字
  const textY = centerY + totalHeight / 2 - 12
  ctx.font = 'bold 12px Arial'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  ctx.fillStyle = '#333333'
  ctx.fillText(props.centerText, centerX, textY)
}

onMounted(() => {
  generateQRCode()
})
</script>
